package net.caidingke.shepherd.utils.http;

import com.google.common.base.Strings;
import net.caidingke.shepherd.utils.collection.CollectionUtil;
import net.caidingke.shepherd.utils.misc.IdGenerator;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author bowen.
 */
public class CookieHelper {

    public static final String COOKIE_NAME = "SHEPHERD_ID";

    public static final String LOCAL = "localhost";

    public static final String COLON = ":";

    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieValue) throws IOException {
        Cookie cookie = getCookie(request, COOKIE_NAME);
        if (cookie == null) {
            cookie = new Cookie(COOKIE_NAME, cookieValue);
        }
        cookie.setValue(cookieValue);
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    /**
     * 设置Cookie值，随机生成一个Cookie
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public static String setCookie(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String cookieValue = IdGenerator.uuid();
        setCookie(request, response, cookieValue);
        return cookieValue;
    }

    /**
     * 获取Cookie，如果为空则设置Cookie，并返回Cookie值
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public static String getCookieValueIfNullThenSetCookie(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String cookieValue = getCookieValue(request);
        if (Strings.isNullOrEmpty(cookieValue)) {
            cookieValue = setCookie(request, response);
        }
        return cookieValue;
    }

    /**
     * 获取Cookie值
     * @param request
     * @return
     */
    public static String getCookieValue(HttpServletRequest request) {
        Cookie cookie = getCookie(request, COOKIE_NAME);
        if (cookie != null) {
            return cookie.getValue();
        } else {
            return null;
        }
    }

    /**
     * 移除Cookie值
     * @param request
     * @param response
     */
    public static void removeCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = getCookie(request, COOKIE_NAME);
        if (cookie == null) {
            return;
        }
        cookie.setValue(null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 获取Cookie对象
     * @param request
     * @param cookieName
     * @return
     */
    private static Cookie getCookie(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (CollectionUtil.isEmpty(cookies)) {
            return null;
        }

        Cookie ticket = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                ticket = cookie;
                break;
            }
        }
        return ticket;
    }

    private static String getDomainName(HttpServletRequest request) {
        String domainName = null;
        String serverName = request.getRequestURL().toString();
        if (Strings.isNullOrEmpty(serverName)) {
            domainName = "";
        } else {
            serverName = serverName.toLowerCase();
            serverName = serverName.substring(7);
            final int end = serverName.indexOf("/");
            serverName = serverName.substring(0, end);
            final String[] domains = serverName.split("\\.");
            int len = domains.length;
            if (len > 3) {
                // www.xxx.com.cn
                domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
            } else if (len <= 3 && len > 1) {
                // xxx.com or xxx.cn
                domainName = "." + domains[len - 2] + "." + domains[len - 1];
            } else {
                domainName = serverName;
            }
        }

        if (domainName.indexOf(COLON) > 0) {
            String[] ary = domainName.split("\\:");
            domainName = ary[0];
        }
        return domainName;
    }
}
